package com.longcai.controller;

import com.longcai.bean.ApiResult;
import com.longcai.bean.PageHelper;
import com.longcai.entity.sys.SysUser;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.SysUserService;
import com.longcai.util.UserUtil;
import com.longcai.vo.SysUserVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ZJ
 * @since 2019-03-16
 */
@RestController
@RequestMapping("/users/")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "当前登陆用户")
    @GetMapping(value = "/current")
    public SysUser currentUser() {
        return UserUtil.getLoginUser();
    }

    @ApiOperation(value = "用户列表")
    @GetMapping(value = "sysUserlist")
    public PageTableResponse sysUserlist(SysUser sysUser, PageHelper pageHelper) {

        return this.sysUserService.sysUserlistPage(sysUser, pageHelper);
    }

    @ApiOperation(value = "根据用户id获取用户")
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('sys:user:query')")
    public ApiResult user(@PathVariable Long id) {

        return this.sysUserService.getSysUserById(id);
    }

    /**
     * 修改用户
     *
     * @param sysUserVo
     * @return
     */
    @PutMapping(value = "updateSysUser")
    @ApiOperation(value = "修改用户")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public SysUser updateSysUser(@RequestBody SysUserVo sysUserVo) {
        return this.sysUserService.updateSysUser(sysUserVo);
    }

    @PostMapping(value = "saveSysUser")
    @ApiOperation(value = "保存用户")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public SysUser saveSysUser(@RequestBody SysUserVo sysUserVo) {
        SysUser u = this.sysUserService.getUser(sysUserVo.getUsername());
        if (u != null) {
            throw new IllegalArgumentException(sysUserVo.getUsername() + "已存在");
        }

        return sysUserService.saveSysUser(sysUserVo);
    }

    /**
     * 密码修改
     * @param sysUser
     * @return
     */
    @PutMapping(value = "updatePassword")
    @ApiOperation(value = "修改密码")
    @PreAuthorize("hasAuthority('sys:user:add')")
    public ApiResult updatePassword(@RequestBody SysUser sysUser){
        return this.sysUserService.updatePassword(sysUser,sysUser.getNewPassword());
    }

}

